package cn.lvhang.org.controller;

import cn.lvhang.basic.util.AjaxResult;
import cn.lvhang.basic.util.PageList;
import cn.lvhang.org.domain.Department;
import cn.lvhang.org.query.DepartmentQuery;
import cn.lvhang.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //  =  @Controller +@ResponseBody
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")//用于对swagger字段的描述
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    //新增或修改部门
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")//用于对swagger字段的描述
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.add(department);
            }else{
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }
    //删除部门
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }
    //查询单个部门
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }
    //查询所有部门
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.queryAll();
    }
    //分页 + 高级查询
    // @RequestBody接收前台发送的json字符串
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }
    //批量删除
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }
    //获取部门树
    @GetMapping("/tree")
    public List<Department> loadTree(){
        return departmentService.loadTree();
    }
}
